package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.database.entity.MistyGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 幻境工作
class MistyWork(
    private val config: MistyGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "幻境"

    override suspend fun executeWork(): WorkResult {
        try {
            // 1. 先查询幻境信息
            val queryResult = gameApi.queryMisty()
            return queryResult.foldWithApiException(
                onSuccess = { response ->
                    if (response.curStage > 0) {
                        // 如果curStage > 0，执行挑战-退出部分
                        executeChallengeAndExit()
                    } else if (response.getUsedChallengeTimes() > 0) {
                        // 如果getUsedChallengeTimes() > 0，选场景开始挑战
                        val stageId = config.getStageId()
                        if (stageId == null) {
                            historyManager.addHistory(name, "关卡解析失败，当前配置为${config.selectedMistyText}")
                            return WorkResult.Failure(Exception("关卡解析失败"), "关卡解析失败")
                        }
                        
                        val startResult = gameApi.startMisty(stageId)
                        startResult.foldWithApiException(
                            onSuccess = { startResponse ->
                                executeChallengeAndExit()
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 执行挑战-退出部分
     */
    private suspend fun executeChallengeAndExit(): WorkResult {
        return try {
            // 一直挑战直至msg==-1
            var shouldContinue = true
            var lastCode: Int = 0
            while (shouldContinue) {
                val fightResult = gameApi.fightMisty()
                fightResult.foldWithApiException(
                    onSuccess = { fightResponse ->
                        historyManager.addHistory(name, fightResponse.getDescription())
                    },
                    onFailure = { code, msg ->
                        lastCode = code
                        historyManager.addHistory(name, msg, if (code != -1) code else 0)
                        shouldContinue = false // 出错时也退出
                    }
                )
            }

            if (lastCode == -1) {
                // 退出挑战
                val endResult = gameApi.endMisty()
                endResult.foldWithApiException(
                    onSuccess = { endResponse ->
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                    }
                )
            } else {
                historyManager.addHistory(name, "幻境异常，停止该任务")
            }

            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}